/**
 * Created by Ado on 2015/6/24.
 */
class DukeNode extends egret.HashObject{
    private _children:DukeNode[];
    private _parentNode:DukeNode;
    public data:GameUnit;
    public constructor(){
        super();
        this._children = [];
    }

    public addChild(node:DukeNode){
        if( this._children.indexOf(node) == -1){
            this._children.push(node);
            node.setParentNode(this);
        }
    }

    public removeChild(node:DukeNode){
        var idx:number = this._children.indexOf(node);
        if( idx != -1){
            this._children.splice(idx,1);
            node.setParentNode(null);
        }
    }

    public children():DukeNode[]{
        return this._children;
    }

    public isRoot():boolean{
        return this._parentNode == null;
    }

    public getParentNode():DukeNode{
        return this._parentNode;
    }

    public setParentNode(node:DukeNode){
        this._parentNode = node;
    }

    public isChildRoot():boolean{
        return this._children.length > 1;
    }

    public isLeaf():boolean{
        return this._children.length == 0 && this._parentNode != null;
    }
    public resetChildren(){
        var node:DukeNode;
        while(this._children.length != 0){
            node = this._children.pop();
            node.resetChildren();
            node.reset();
        }
        DukeTree.reclaimNode(this);
    }
    public removeSelf(){
        if( this._parentNode != null)
            this._parentNode.removeChild(this);
        if( this.data && this.data.parent != null){
            this.data.parent.removeChild(this.data)
            GameMain.instance().reclaimUnit(this.data);
        }
        DukeTree.reclaimNode(this);
    }
    public reset():void{
        this._parentNode = null;
        this._children = [];
        this.data = null;
    }
}